
package restlet.android;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.cse210.grocerwe.client.SGroup;
import com.cse210.grocerwe.client.SItem;


public class BuildListActivity extends Activity
{
    private static final int NEW_ITEM_DIALOG = 1;
    private static final int EDIT_ITEM_DIALOG = 2;
    private final int GO_SHOPPING = 0x01;
    private final String TAG = "BuildListActivity";
    private final boolean LIVE = true;
    private String user = null;
	private GrocerResource resource = new GrocerResource();
    private ExpandableListAdapter expandableListAdapter;
    private GrocerWeListObserver listObserver;
    private Vibrator systemVibrator;
    private ProgressDialog pd;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	System.setProperty("java.net.preferIPv6Addresses", "false");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        systemVibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        
        Bundle b = getIntent().getExtras();
        user = b.getString("username");

        // Retrieve the ExpandableListView from the layout
        ExpandableListView listView = (ExpandableListView) findViewById(R.id.listView);
        Button addItemButton = (Button) findViewById(R.id.AddItemButton);
        Button shopButton = (Button) findViewById(R.id.ShopButton);
        Button refreshButton = (Button) findViewById(R.id.RefreshButton);
                
        addItemButton.setOnClickListener(new OnClickListener()
        {            
            @Override
            public void onClick(View v)
            {
                systemVibrator.vibrate(50);
                showDialog(NEW_ITEM_DIALOG, null);
            }
        });
        
        shopButton.setOnClickListener(new OnClickListener()
        {            
            @Override
            public void onClick(View v)
            {
                //Toast.makeText(getBaseContext(), "Going Shopping", Toast.LENGTH_SHORT).show();
            	Log.v(TAG, "Going Shopping from main activity");
                Intent myIntent = new Intent (BuildListActivity.this, GoShoppingActivity.class);
                BuildListActivity.this.startActivityForResult(myIntent, GO_SHOPPING);
                systemVibrator.vibrate(50);
            }
        });
        
        refreshButton.setOnClickListener(new OnClickListener()
        {            
            @Override
            public void onClick(View v)
            {
                systemVibrator.vibrate(50);
                //refreshLists();
                pd = ProgressDialog.show(BuildListActivity.this, "", 
                        "Refreshing Lists. Please wait...", false);
                new RefreshListsTask().execute(null, null, null);
            }
        });
        
        

        // Initialize the expandableListAdapter with blank groups and children
        // We will be adding children on a thread, and then update the ListView
        expandableListAdapter = new ExpandableListAdapter(BuildListActivity.this, new ArrayList<SGroup>(),
                new ArrayList<ArrayList<SItem>>());
        
        listObserver = new GrocerWeListObserver();        
        expandableListAdapter.registerDataSetObserver(listObserver);

        // Set this blank expandableListAdapter to the list view
        listView.setAdapter(expandableListAdapter);
        listView.setFocusable(false);
        listView.setClickable(false);
        
        //refreshLists();
        pd = ProgressDialog.show(BuildListActivity.this, "", 
                "Refreshing Lists. Please wait...", false);
        new RefreshListsTask().execute(null, null, null);
    }
    
    @Override
    protected Dialog onCreateDialog(int id, Bundle b) {
    	// This example shows how to add a custom layout to an AlertDialog
        LayoutInflater itemFactory = LayoutInflater.from(this);
        final View itemDialog = itemFactory.inflate(R.layout.item_dialog, null);
        final EditText name = (EditText) itemDialog.findViewById(R.id.item_name_edit);
        final EditText description = (EditText) itemDialog.findViewById(R.id.item_description_edit);
        final EditText amount = (EditText) itemDialog.findViewById(R.id.item_amount_edit);
        final Spinner type = (Spinner) itemDialog.findViewById(R.id.category_spinner);
        final Spinner list = (Spinner) itemDialog.findViewById(R.id.list_spinner);
        final ArrayAdapter<String> whichListAdapter;
        final ArrayList<String> listNames = new ArrayList<String>();
        final ArrayAdapter<String> whichTypeAdapter;
        String[] categories = getResources().getStringArray(R.array.categories);
        final ArrayList<String> listTypes = new ArrayList<String>(Arrays.asList(categories));
        final String itemKey = (b != null)?b.getString("itemKey"):null;
        
        //populate the drop down with our group names
        int groupCount = expandableListAdapter.getGroupCount();            
        for(int i = 0; i < groupCount; i++){
        	SGroup mGroup = (SGroup) expandableListAdapter.getGroup(i);
        	if (!mGroup.getName().equals("Purchased for Me") && 
        			!mGroup.getName().equals("Purchased by Me")){
        		listNames.add(mGroup.getName());
        	}
        }
        
        whichListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, 
        		listNames);
        whichListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        list.setAdapter(whichListAdapter);
        
        whichTypeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, 
        		listTypes);
        whichTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        type.setAdapter(whichTypeAdapter);

        if (b != null){
        	name.setText(b.getString("name"));
        	description.setText(b.getString("description"));
        	amount.setText(b.getString("amount"));
        	type.setSelection(listTypes.indexOf(b.getString("type")));
        	list.setSelection(listNames.indexOf(b.getString("list")));
        }        
        
        //add a tag for the calling activity
        itemDialog.setTag(BuildListActivity.this);
        
        switch (id) {
        case NEW_ITEM_DIALOG:
            return new AlertDialog.Builder(BuildListActivity.this)
            	.setTitle(R.string.AddItemDialogTitle)
                .setView(itemDialog)
                .setPositiveButton(R.string.DialogOk, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	if(name.getText().toString() != null){
	                    	BuildListActivity caller = (BuildListActivity) itemDialog.getTag();
	                    	String key = caller.getGroupKeyFromName(list.getSelectedItem().toString());
	                    	SItem item = new SItem( name.getText().toString(), 
	                    							type.getSelectedItem().toString(),
	                    							amount.getText().toString(), 
	                    							description.getText().toString(),
	                    							user, 
	                    							key);
	                    	dialog.dismiss();
	                    	caller.resource.addItem(item);
	                    	//caller.refreshLists();
	                    	pd = ProgressDialog.show(BuildListActivity.this, "", 
	                                "Refreshing Lists. Please wait...", false);
	                    	new RefreshListsTask().execute(null, null, null);
	                    	removeDialog(NEW_ITEM_DIALOG);
                    	}
                    }
                })
                .setNegativeButton(R.string.DialogCancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	dialog.dismiss();
                    	removeDialog(NEW_ITEM_DIALOG);
                    }
                })
                .create();
        case EDIT_ITEM_DIALOG:
            return new AlertDialog.Builder(BuildListActivity.this)
            	.setTitle(R.string.EditItemDialogTitle)
                .setView(itemDialog)
                .setPositiveButton(R.string.DialogOk, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	if(name.getText().toString() != null){
	                    	BuildListActivity caller = (BuildListActivity) itemDialog.getTag();
	                    	String key = caller.getGroupKeyFromName(list.getSelectedItem().toString());
	                    	SItem item = new SItem( itemKey, 
	                    			name.getText().toString(), 
	                    			type.getSelectedItem().toString(), 
	                    			null, 
	                    			0, 
	                    			amount.getText().toString(),
	                    			description.getText().toString(), 
	                    			user, 
	                    			null, 
	                    			key, 
	                    			false,
	                    			SItem.ST_NORMAL);
	                    	
	                    	dialog.dismiss();
	                    	caller.resource.editItem(item);
//	                    	/caller.refreshLists();
	                    	pd = ProgressDialog.show(BuildListActivity.this, "", 
	                                "Refreshing Lists. Please wait...", false);
	                    	new RefreshListsTask().execute(null, null, null);
	                    	removeDialog(EDIT_ITEM_DIALOG);
                    	}
                    }
                })
                .setNegativeButton(R.string.DialogCancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	dialog.dismiss();
                    	removeDialog(EDIT_ITEM_DIALOG);
                    }
                })
                .create();
        }
        return null;
    }
    
    public String getUser(){
    	return user;
    }    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Toast.makeText(getBaseContext(), "Got Back!", Toast.LENGTH_SHORT).show();
        Log.v(TAG, "Got back from shopping activity");
        if (LIVE)
        {
        	Log.v(TAG, "Refreshing main listview");
            //refreshLists();
        	pd = ProgressDialog.show(BuildListActivity.this, "", 
                    "Refreshing Lists. Please wait...", false);
            new RefreshListsTask().execute(null, null, null);
        }
    }
    
    private String getGroupKeyFromName(String name)
    {
    	String key = null;
    	SGroup[] myGroups = resource.getGroups(user);
    	
        for(SGroup group: myGroups){
        	if(group.getName().equals(name)){
        		key = group.getKey();
        	}

        }    	
        return key;
    }
    
    public class GrocerWeListObserver extends DataSetObserver
    {
    	public void itemDeleted(SItem item){
    		resource.removeItem(item.getKey());
    		//refreshLists();
    		pd = ProgressDialog.show(BuildListActivity.this, "", 
                    "Refreshing Lists. Please wait...", false);
    		new RefreshListsTask().execute(null, null, null);
    	}
    	public void itemEdited(SItem item){
    		systemVibrator.vibrate(50);
    		Bundle b = new Bundle();
    		b.putString("name", item.getName());
    		b.putString("description", item.getDescription());
    		b.putString("amount", item.getQuantitySize());
    		b.putString("type", item.getType());
    		b.putString("list", item.getGroup());
    		b.putString("itemKey", item.getKey());
            showDialog(EDIT_ITEM_DIALOG, b);
    	}
    };
    
    private class RefreshListsTask extends AsyncTask<Void, Void, Void>{
		protected Void doInBackground(Void... params) {
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()){
	        	expandableListAdapter.clearList();
	        	
	        	SGroup forMeGroup = new SGroup("Purchased for Me", user, true);
	        	SGroup byMeGroup = new SGroup("Purchased by Me", user, true);
	        	expandableListAdapter.addGroup(forMeGroup);
	        	expandableListAdapter.addGroup(byMeGroup);
	        	
	        	SGroup[] myGroups = resource.getGroups(user);
	        	
	            for(SGroup group: myGroups){
	            	expandableListAdapter.addGroup(group);
	            	
	            	SItem[] thisGroupsItems = resource.retrieveList(group.getKey());
	            	for(int i=0; i < thisGroupsItems.length; i++){
	            		SItem item = thisGroupsItems[i];
	            		
	            		if(item.getBuyer() != null && item.getOwner().equals(user))
	    				{
	            			expandableListAdapter.addItemToGroup(item, forMeGroup);
	    				}
	    				else if(item.getBuyer() != null && item.getBuyer().equals(user) && !item.getOwner().equals(user))
	    				{
	    					expandableListAdapter.addItemToGroup(item, byMeGroup);
	    				}
	    				else if(item.getStatus() != SItem.ST_NORMAL)
	    				{
	    					//ignore this item. it's either being shopped or is purchased
	    				}
	    				else
	    				{
	    					expandableListAdapter.addItemToGroup(item, group);
	    				}
	            	}
	            }
			}
			else {
//				runOnUiThread (Toast.makeText(getBaseContext(), 
//						"Please Check Network Connection", Toast.LENGTH_SHORT).show());
				
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(BuildListActivity.this,
								"Please Check Network Connection", 
								Toast.LENGTH_SHORT).show();
						}
					}
				);
				
				
			}

            return null;
		}
		
    	protected void onPostExecute(Void result) {
    		if(pd != null){
    			pd.dismiss();
    			expandableListAdapter.notifyDataSetChanged();
    		}
        }
    };
}
